var express = require('express');
var router = express.Router();
var md5 = require("md5");

var buyerDAO = require("../bin/buyerDAO.js");
var Good = require("../bin/goodsDAO.js");
var Buycar = require("../bin/buycarDAO.js");

var ccap = require("ccap");
var captcha = ccap({
  width: 100,
  height: 30,
  offset: 20,
  quality: 100,
  fontsize: 30,
  generate: function () {
    var sourceStr = "1234567890";
    var text = "";
    for (var i = 0; i < 4; i++) {
      var index = Math.floor(Math.random() * sourceStr.length);
      var ch = sourceStr[index];
      text += ch;
    }
    return text;
  }
});

// 导入并配置multer
var multer = require("multer");
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/avatar');
  },
  filename: function (req, file, cb) {
    var fileName = req.session.user._id + "." + file.mimetype.split("/")[1];
    req.userAvatar = fileName;
    cb(null, fileName);
  }
});
var upload = multer({ storage: storage });

var storage1 = multer.diskStorage({

  destination: function (req, file, cb) {

    cb(null, "./public/avatar")
  },
  filename: function (req, file, cb) {
    if (!req.pics) {
      req.pics = [];
    }
    var time = Date.now();
    var suffix = file.mimetype.split("/")[1];
    var fn = time + "." + suffix;
    req.pics.push(fn);
    // console.log(req.pics)
    cb(null, fn);
  }
});
var upload1 = multer({
  storage: storage1
});


router.get("/captcha", (req, res) => {
  var arr = captcha.get();
  // console.log(arr[0]);
  req.session.captcha = arr[0];
  res.set("Content-Type", "image/jpeg");
  res.send(arr[1]);
});
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});
router.get('/tupian', function (req, res) {
  var imgs = [
    { img: "/images/1.jpg" },
    { img: "/images/logo.png" },
    { img: "/images/14.jpg" },
    { img: "/images/15.jpg" },
    { img: "/images/16.jpg" }
  ]
  res.json({ imgs });
});
router.get('/lunkuo', function (req, res) {
  var imgs = [
    { img: "/images/2.jpg" },
    { img: "/images/3.jpg" },
    { img: "/images/4.jpg" },
    { img: "/images/5.jpg" }
  ]
  res.json({ imgs });
});
router.get('/lei', function (req, res) {
  var imgs = [
    { img: "/images/6.jpg", txt: "限量抢", lianlie1: "/user/myself", lianlie2: "" },
    { img: "/images/7.jpg", txt: "品牌馆", lianlie1: "/user/myself", lianlie2: "" },
    { img: "/images/8.jpg", txt: "会员专区", lianlie1: "/user/myself", lianlie2: "" },
    { img: "/images/9.jpg", txt: "排行榜", lianlie1: "/user/myself", lianlie2: "" },
    { img: "/images/10.jpg", txt: "分类", lianlie1: "/user/fenlei", lianlie2: "/user/fenlei" },
    { img: "/images/11.jpg", txt: "购物车", lianlie1: "/user/login", lianlie2: "/user/shopping" },
    { img: "/images/12.jpg", txt: "个人中心", lianlie1: "/user/login", lianlie2: "/user/myself" },
    { img: "/images/13.jpg", txt: "购物须知", lianlie1: "/user/myself", lianlie2: "" }
  ]
  res.json({ imgs });
});
router.get('/liu', function (req, res) {
  var imgs = [
    { img: "/images/17.jpg" },
    { img: "/images/18.jpg" },
    { img: "/images/19.jpg" },
    { img: "/images/20.jpg" },
    { img: "/images/21.jpg" },
    { img: "/images/22.jpg" },
  ]
  res.json({ imgs });
});

// 注册请求
router.post('/regist', function (req, res) {
  if (req.body.captcha.toUpperCase() != req.session.captcha) {
    res.json({ err: 1, msg: "验证码错误" });
  } else {
    buyerDAO.findOne({ username: req.body.username })
      .then(data => {
        if (data) {
          res.json({ err: 1, msg: '该用户名已被占用' });
        } else {
          var u = new buyerDAO(req.body);
          u.psw = md5(u.psw);
          u.save()
            .then(data1 => {
              res.json({ err: 0, msg: '注册成功' });
            });
        }
      });
  }
});

// 登陆请求
router.post("/login", (req, res) => {
  req.body.psw = md5(req.body.psw);
  buyerDAO.findOne(req.body)
    .then(data => {
      // console.log(data)
      if (!data) {
        res.json({ err: 1, msg: "用户名不存在" });
      } else {
        req.session.user = data;
        res.json({ err: 0, msg: "登录成功", userInfo: req.session.user });
      }
    });
});
// 上传头像
router.post("/upload", upload.single("header"), (req, res) => {
  // console.log(req.session.user)
  buyerDAO.findOne({ username: req.session.user.username }, function (err, data) {
    req.session.user.avatar=req.userAvatar;
    data.avatar = req.userAvatar;
    data.save(function (err) {
      res.json({ err: 0, msg: "上传成功" });
    });
  });
});
// 查询个人信息
router.post("/self", (req, res) => {
  buyerDAO.findOne({ _id: req.session.user._id })
    .then(data => {
      if (!data) {
        // console.log(123)
        res.json({ err: 1, msg: "用户名不存在" });
      } else {
        // console.log(456)
        // console.log(req.session.user)
        res.json({ err: 0, msg: "登录成功", userInfo: req.session.user });
      }
    });
});
// 判断是否登录
router.get("/islogin", (req, res) => {
  if (req.session.user) {
    // console.log(req.session.user)
    res.json({ err: 0, userInfo: req.session.user });
  }
});

// 退出登录
router.get("/exit", (req, res) => {
  req.session.user = null;
  res.json({ err: 0, msg: "退出成功" });
});

//上传商品接口
router.post("/shangchuan", upload1.array("pic"), function (req, res) {

  var goodInfo = JSON.parse(req.body.info);
  // console.log(goodInfo.type);
  // console.log(req.pics);
  goodInfo.pics = req.pics;
  // console.log(goodInfo)
  var g = new Good(goodInfo);
  g.save()
    .then(err => {
      res.json({ err: 0, msg: "上传成功" });
    });
});

//搜索商品接口
router.post("/search", function (req, res) {
  var reg = new RegExp(req.body.shopname);
  // console.log(req.body)
  Good.find({ name: reg }).sort({price:req.body.size})
    .then(data => {
      // console.log(data)
      res.json({ err: 0, data: data });
    })
});

// 查询单个商品信息
router.post("/onegood", function (req, res) {
  // console.log(123)
  Good.findOne({ _id: req.body._id })
    .exec(function (err, data1) {
      // console.log(data1)
      res.json({ data1 });
    })
})
// 查询所有商品信息
router.post("/suoyou", function (req, res) {
  var num=6;
  // console.log(req.body)
  Good.find().sort({price:1}).skip(req.body.page*num).limit(num)
    .exec(function (err, data1) {
      // console.log(data1)
      res.json({ data1 });
    })
})
// 商品分类(大分类)
router.post("/fenlei", function (req, res) {
  // console.log(123)
  Good.find()
    .exec(function (err, data) {
      var data1 = [];
      for (var i = 0; i < data.length; i++) {
        // console.log(data[1].type[0].name)
        for (var j = 0; j < data[i].type.length; j++) {
          data1.push(data[i].type[j].name)
        }
      }
      for (var i = 0; i < data1.length; i++) {
        for (var j = i + 1; j < data1.length; j++) {
          if (data1[i] == data1[j]) {
            // console.log(i)
            data1.splice(j, 1);
            j--;
          }
        }
      }
      res.json({ data1 });
    })
})
// 商品小分类
router.post("/sfenlei", function (req, res) {
  // console.log(req.body.bigkind)
  Good.find()
    .exec(function (err, data) {
      var data1 = [];
      for (var i = 0; i < data.length; i++) {
        // console.log(data[1].type[0].name)
        for (var j = 0; j < data[i].type.length; j++) {
          if (data[i].type[j].name == req.body.bigkind) {
            for (var m = 0; m < data[i].type[j].kind.length; m++)
              data1.push(data[i].type[j].kind[m])
          }
        }
      }
      for (var i = 0; i < data1.length; i++) {
        for (var j = i + 1; j < data1.length; j++) {
          if (data1[i] == data1[j]) {
            // console.log(i)
            data1.splice(j, 1);
            j--;
          }
        }
      }
      res.json({ data1 });
      // console.log(data1)
    })
})
// 分类查商品
router.post("/good", function (req, res) {
  // console.log(req.body.str)
  Good.find().sort({price:1})
    .exec(function (err, data) {
      var data1 = [];
      for (var i = 0; i < data.length; i++) {
        // console.log(data[1].type[0].name)
        for (var j = 0; j < data[i].type.length; j++) {
          for (var n = 0; n < data[i].type[j].kind.length; n++) {
            if (data[i].type[j].kind[n] == req.body.str) {
              data1.push(data[i])
            }
          }

        }
      }
      res.json({ data1 });
      // console.log(data1)
    })
})
// ------------------------------------------------------------------------------------------
// 加入购物车
router.post("/caradd", (req, res) => {
  // console.log(req.body)
  Buycar.findOne({ goods: req.body._id,buyer: req.session.user._id })
    .then(data => {
      if (data) {
        Buycar.update({ goods: data.goods }, {
          gnum: data.gnum + 1
        }, function (err) {
          res.json({ msg: "添加成功" })
        })
      } else {
        var b = new Buycar({
          goods: req.body._id,
          buyer: req.session.user._id,
          gnum: 1
        });
        b.save()
          .then(data => {
            // console.log(data)
            res.json({ err: 0, msg: "添加成功" });
          });
      }
    })


})
// 查询购物车
router.post("/findcar", (req, res) => {
  Buycar.find({ buyer: req.session.user._id })
    .populate({ path: "goods" })
    .then(data => {
      // console.log(data)
      res.json({ err: 0, data: data });
    });
});

// 删除购物车商品
router.post("/delete", (req, res) => {
  Buycar.remove({ goods: req.body._id })
    .then(data => {
      if (data) {
        res.json({ err: 0, msg: "删除成功" });
      } else {
        res.json({ err: 1, msg: "删除失败" });
      }
    })
});
module.exports = router;
